<?php
require_once("{$CfgPara->root}/class/user_operate.class.php");
require_once("{$CfgPara->root}/class/do_edit_img.func.php");
require_once("{$CfgPara->root}/class/mysql.func.php");
require_once("{$CfgPara->root}/class/make_img_name.class.php");

/**
 * topic 专题数据模型
 *
 * @version 1.0
 * @author Human
 */
class topic_m
{
    /**
     * 列表类型 广场
     */
    const ListPublic = 1;
    /**
     * 列表类型 关注
     */
    const ListUp = 2;
    /**
     * 列表类型 参与
     */
    const ListJoin = 3;
    /**
     * 列表类型 我的专题
     */
    const ListMine = 10;
    /**
     * 列表类型 投稿专题选择
     */
    const ListJoinSele = 11;
    /**
     * 列表类型 管理员编辑列表
     */
    const ListEdit = 12;
    /**
     * 列表类型 管理员待审核列表
     */
    const ListCheck = 13;
    /**
     * 列表类型 管理员已审核列表
     */
    const ListChecked = 14;

    /**
     * @var int 获取专题列表时 如果设置了计算总数
     * 则为总数量，如果没设置为-1 如果计算时错误为-2
     */
    public $topic_list_count;
    /**
     * @var bool 当前是否为PC版本 默认为false
     */
    public $is_tablet = FALSE;

    public function __construct($dbPara = NULL)
    {
        if ($dbPara != null) {
            db_connect($dbPara);
        }
    }

    /**
     * 获取用户参与的专题数 如果$user_id参数为0 则获取总专题数
     * @param mixed $user_id
     * @return mixed
     */
    public function topic_count($user_id = 0)
    {
        if ($user_id > 0) {
            $result1 = db_query("SELECT `TopicCount` FROM `users` WHERE `Id` = {$user_id}");
        } elseif ($user_id == 0) {
            $result1 = db_query("SELECT Count(1) FROM `topic`");
        } else {
            return "查询专题数量时 提交信息错误";
        }

        if ($result1 !== false) {
            $result = $result1->fetch_array();
            return $result[0];
        } else {
            return db_error();
        }
    }

    /**
     * 获取专题中某作者的作品数 错误时会返回0
     * @param int $user_id 用户id
     * @param int $topic_id 专题id
     * @return int
     */
    public function topic_work_count($user_id, $topic_id)
    {
        if (!is_numeric($user_id) || !is_numeric($topic_id)) {
            return '提交的用户信息或专题信息错误';
        }
        $sql_str = "SELECT Count(*) FROM topic_works, works WHERE 
					works.Author = {$user_id} AND 
					works.State = 1 AND 
					topic_works.State = 1 AND 
					topic_works.TopicId = {$topic_id} AND 
					topic_works.WorkId = works.Id";
        $result = db_query($sql_str);
        if ($result !== FALSE) {
            return $result->fetch_array()[0];
        } else {
            return 0;
        }
    }

    /**
     * 获取信息 正确返回对象，错误返回错误信息
     */
    public function topic_msg($topic_id)
    {
        if (!is_numeric($topic_id)) {
            return "错误:提交的专题信息错误";
        }
        $result1 = db_query("SELECT * FROM `topic` WHERE `Id` = '{$topic_id}'");
        if ($result1 instanceof mysqli_result) {
            $result = $result1->fetch_object();
            return $result;
        } else {
            return db_error();
        }
    }

    /**
     * 获取专题图片 返回文件名数组
     * @param string 专题的图片存储字符串
     */
    public function topic_imgs($img_text)
    {
        $topicImg_temp = explode(";", $img_text);
        $topicImg_count = count($topicImg_temp);
        if ($topicImg_count > 9) {
            for ($i = 10; $i <= $topicImg_count; $i++) {
                unset($topicImg_temp[$i]);
            }
        }
        if ($topicImg_count > 0) {
            return $topicImg_temp;
        } else {
            return false;
        }
    }

    /**
     * 专题列表 成功返回作品对象数组 错误返回错误信息
     * @param int $type 列表的类型 请查看本类的列表类型常量
     * @param int $id 相关内容的id 我的专题:用户id 投稿专题选择:作品id
     * @param int $page 当前页索引 1最小
     * @param int $page_size 每页条目数
     * @param string $search 搜索的文本
     * @param bool $count 是否同时计算总数
     * @return mixed
     */
    function topic_list($type, $id, $page, $page_size, $search = null, $count = false)
    {
        if (!is_numeric($type) || !is_numeric($id) || !is_numeric($page) || !is_numeric($page_size)) {
            return "错误:专题列表查询信息错误";
        }
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        if ($search != null && is_string($search))  //加入全文检索语句
        {
            $search_text = urldecode($search);
            $search_text = db_escape($search_text);
            if (mb_strlen($search_text) < 2) {
                return "搜索文本长度应大于1";
            }
            if ($search_text !== false) {
                $search_sql = "AND MATCH (`topic`.`Keyword`) AGAINST ('{$search_text}') ";
            } else {
                $search_sql = '';
            }
        } else {
            $search_sql = '';
        }
        if ($count === true) //同时计算检索总数 而不受limit影响
        {
            $found_rows_sql = 'SQL_CALC_FOUND_ROWS';
        } else {
            $this->topic_list_count = -1;
            $found_rows_sql = '';
        }
        if ($type == topic_m::ListPublic) {
            if ($search_sql != '') {
                $sql_str = "SELECT {$found_rows_sql} * FROM `topic` WHERE MATCH (`topic`.`Keyword`) AGAINST ('{$search_text}')";
            } else {
                if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])) {
                    $sql_str = "SELECT {$found_rows_sql} `topic`.*, `topic_up`.`UserId` FROM `topic` LEFT JOIN `topic_up` 
	                            ON `topic`.`Id` = `topic_up`.`TopicId` AND `topic_up`.`UserId` = {$_SESSION['user_id']}";
                } else {
                    $sql_str = "SELECT {$found_rows_sql} * FROM `topic`";
                }
            }
        } elseif ($type == topic_m::ListUp) {
            // 20170120 修改 专题关注的列表 专题的信息只需要专题Id和名称，专题下的最新作品的Id、图片、作品名、作者、推荐数
            if (!(isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']))) {
                $result = array(); //如果当前用户没登陆，直接返回空数组
                return $result;
            }
            global $isTablet;
            $sql_str = "SELECT $found_rows_sql topic.Id as TopicId,topic.`Name` as TopicName,
                               works.Id as WorkId,works.Picture,works.`Name` as WorkName,works.UpCount,
                               users.`Name` as UserName
                        FROM topic 
                        inner join topic_up
                        ON topic.Id = topic_up.TopicId AND topic_up.UserId = {$_SESSION['user_id']}
                        left join works 
                        ON topic.LastWorkId = works.Id 
                        left join users
                        ON works.Author = users.Id";
        } elseif ($type == topic_m::ListJoin) {
            if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']))
                $sql_str = "SELECT {$found_rows_sql} DISTINCT `topic`.*, `topic_up`.`UserId` as UserId 
                            FROM `topic` 
                            INNER JOIN `topic_works`
	                            ON `topic`.`Id` = `topic_works`.`TopicId` {$search_sql}
                            INNER JOIN `works`
	                            ON `works`.`Id` = `topic_works`.`WorkId` AND `works`.`Author` = {$_SESSION['user_id']} 
                            LEFT JOIN `topic_up` 
	                            ON `topic`.`Id` = `topic_up`.`TopicId` 
	                            AND `topic_up`.`UserId` = {$_SESSION['user_id']}";
            else {
                $result = array();
                return $result;
            }
        } elseif ($type == topic_m::ListMine) {
            // 显示他参与了的专题 
            $sql_str = "SELECT {$found_rows_sql} DISTINCT `topic`.*, `topic_up`.`UserId` as UserId 
                        FROM `topic` 
                        INNER JOIN `topic_works`
                            ON `topic`.`Id` = `topic_works`.`TopicId` AND
                               `topic_works`.`State` = 1 {$search_sql}
                        INNER JOIN `works`
                            ON `works`.`Id` = `topic_works`.`WorkId` AND `works`.`Author` = {$_SESSION['user_id']} 
                        LEFT JOIN `topic_up` 
                            ON `topic`.`Id` = `topic_up`.`TopicId` 
                            AND `topic_up`.`UserId` = {$_SESSION['user_id']}";
        } elseif ($type == topic_m::ListJoinSele) {
            $sql_str = "SELECT {$found_rows_sql} `topic`.*, `topic_works`.`WorkId`, `topic_works`.`State` as CheckState
                        FROM `topic` 
                        LEFT JOIN `topic_works` 
                        ON `topic`.`Id` = `topic_works`.`TopicId` AND `topic_works`.`WorkId` = {$id} ";
        } elseif ($type == topic_m::ListEdit) {
            $sql_str = "SELECT {$found_rows_sql} * FROM `topic` ";
            if (!empty ($search_sql)) {
                $sql_str .= "WHERE " . substr($search_sql, 4);
            }
        } elseif ($type == topic_m::ListCheck || $type == topic_m::ListChecked) {
            //20170129 新增 专题待审核的列表 专题的信息只需要专题Id和名称，专题下的待审核作品的Id、图片、作品名、作者、推荐数
            if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] < 90 ||
                !isset($_SESSION['user_admin']) || $_SESSION['user_admin'] != 1
            ) {
                $result = array(); //如果当前用户无管理权限 ，直接返回空数组
                return $result;
            }
            if ($type == topic_m::ListCheck) {
                $workState = '0'; //作品状态为待审
                $orderBy = 'ReleaseDt'; //根据投稿时间排序
            } else {
                $workState = '1'; //作品状态为审核通过
                $orderBy = 'CheckDt'; //根据审核通过时间排序
            }
            $sql_str = "SELECT {$found_rows_sql} topic.Id as TopicId,topic.`Name` as TopicName, topic_works.State,
                            works.Id as WorkId,works.Picture,works.`Name` as WorkName,works.UpCount,
                            users.`Name` as UserName
                        FROM topic_works
                        INNER JOIN topic
                        ON topic.Id = topic_works.TopicId AND topic_works.State = {$workState} {$search_sql}
                        LEFT JOIN works 
                        ON works.Id = topic_works.WorkId
                        LEFT join users
                        ON works.Author = users.Id
                        ORDER BY topic_works.{$orderBy} DESC 
                        LIMIT {$limit_offset},{$page_size}";
        } else {
            return '专题列表类型错误';
        }
        if ($type != topic_m::ListCheck && $type != topic_m::ListChecked) //专题审核的列表已经排序了
            $sql_str .= " ORDER BY `topic`.`Id` DESC LIMIT {$limit_offset},{$page_size}";
        $result1 = db_query($sql_str);
        if ($result1 instanceof mysqli_result) {
            $fetch_result = db_fetch_list($result1, $rows);
            if ($count === true) {
                $found_count = db_query('SELECT FOUND_ROWS()');
                if ($found_count !== false) {
                    $this->topic_list_count = $found_count->fetch_array()[0];
                } else {
                    $this->topic_list_count = -2;
                }
            }
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 专题关注 成功返回1 取消关注返回-1 错误返回错误信息
     * @param int $topic_id 作品Id
     */
    function topic_up($topic_id)
    {
        if (!is_numeric($topic_id)) {
            return "错误:推荐信息错误";
        }
        $result = 1;
        $update_type = '+';
        db_begin();
        $result1 = db_query("INSERT INTO `topic_up` SET 
                                                    `TopicId` = '{$topic_id}',
                                                    `UserId` = '{$_SESSION['user_id']}'");
        if ($result1 !== true) {
            if (db_errno() === 1062)//已经推荐过 则取消推荐
            {
                $result = -1;
                $update_type = '-';
                $result2 = db_query("DELETE FROM `topic_up` WHERE 
                                                `TopicId` = '{$topic_id}' AND
                                                `UserId` = '{$_SESSION['user_id']}'");
                if ($result2 === false) {
                    return db_rollback();
                }
            } else {
                return db_rollback();
            }
        }
        $result2 = db_query("UPDATE `topic` SET `UpCount` = `UpCount` {$update_type} 1 WHERE `Id` = '{$topic_id}'");
        if ($result2 !== true) {
            return db_rollback();
        }

        $op = new user_operate();
        $result1 = $op->operate_save($op::TopicUp, $_SESSION['user_id'], $topic_id);
        if ($result1 !== TRUE) {
            db_rollback();
            return $result1;
        }
        db_commit();

        return $result;
    }

    /**
     * 专题关注人员列表 成功返回对象数组 错误返回错误信息
     * @param int $topic_id 专题id
     * @param int $page 当前页
     * @param int $page_size 每页条目数
     */
    function topic_up_list($topic_id, $page, $page_size)
    {
        if (!is_numeric($topic_id)) {
            return "错误:推荐信息错误";
        }
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        $result = db_query("SELECT `topic_up`.*,`users`.`Name` as UserName 
                                        FROM `topic_up`,`users` WHERE `topic_up`.`TopicId` = '{$topic_id}' 
                                                                       AND `topic_up`.`UserId` = `users`.`Id` 
                                        ORDER BY `topic_up`.`UpDt` DESC LIMIT {$limit_offset},{$page_size} ");
        if ($result !== false) {
            $fetch_result = db_fetch_list($result, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 作品投稿到专题 成功返回true 错误返回错误信息
     * @param int $work_id 作品的id
     * @param int $topic_id 专题的id
     */
    function topic_add_work($work_id, $topic_id)
    {
        if (!$_SESSION["user_level"]) {
            return "错误:请登录";
        }
        if (!is_numeric($work_id) || !is_numeric($topic_id)) {
            return "错误:投稿的作品信息或专题信息不正确";
        }
        db_begin();
        //插入作品投稿信息
        $result1 = db_query("INSERT INTO `topic_works` 
                             SET `TopicId` = {$topic_id},
                                 `WorkId` = {$work_id}");
        if ($result1 !== true) {
            if (db_errno() === 1062) {
                //已加入过 查询当前状态 0待审 1通过 -1拒绝
                $result_sele = db_query("SELECT `State`
                                         FROM `topic_works` 
                                         WHERE `TopicId` = {$topic_id} AND 
                                               `WorkId` = {$work_id}");
                if ($result_sele !== FALSE) {
                    if ($row = $result_sele->fetch_object()) {
                        if ($row->State == 0) {//如果为待审 保持当前状态
                            return TRUE;
                        } elseif ($row->State == 1) {//如果为已审核通过 反馈信息
                            db_rollback();
                            return '作品已审核通过加入专题';
                        } else { //被管理员拒绝后 重新再投稿 将状态更新为0待审状态
                            $result_update = db_query("UPDATE `topic_works` 
						                                         SET `State` = 0 
						                                         WHERE `TopicId` = {$topic_id} AND 
						                                               `WorkId` = {$work_id}");
                            if ($result_update === FALSE) {
                                return db_rollback();
                            }
                        }
                    } else {
                        db_rollback();
                        return 'fetch投稿信息时错误';
                    }
                } else {
                    return db_rollback();
                }
            } else
                return db_rollback();
        }
        //更新专题待审核数
        $result2 = db_query("UPDATE `topic` SET `WaitCheckCount` = `WaitCheckCount` + 1 WHERE `Id` = '{$topic_id}' ");
        if ($result2 !== true) {
            return db_rollback();
        }

        db_commit();
        return true;
    }

    /**
     * 专题中作品的审核 审核通过返回'1' 拒绝返回'-1' 错误返回错误信息
     * @param int $work_id 作品的id
     * @param int $topic_id 专题的id
     * @param int $check_mode -1拒绝 1通过
     */
    function topic_add_work_check($work_id, $topic_id, $check_mode)
    {
        if (!isset($_SESSION["user_level"]) || $_SESSION["user_level"] < 90) {
            return "错误:无权限进行审核操作";
        }
        if (!is_numeric($work_id) || !is_numeric($topic_id)) {
            return "错误:提交的作品信息或专题信息不正确";
        }
        if ($check_mode != -1 && $check_mode != 1) {
            return '错误:提交的审核模式不正确';
        }

        db_begin();
        // 获取要加入专题的作品的作者Id
        $userIdResult = db_query("SELECT `Author` FROM `works` WHERE `Id` = {$work_id}");
        if ($userIdResult === false) {
            db_rollback();
            return '获取作者信息时错误';
        } else {
            if ($userIdResult->num_rows > 0 &&
                $userId = $userIdResult->fetch_object()
            ) {
                $user_id = $userId->Author;
            } else {
                db_rollback();
                return '获取作者信息时错误';
            }
        }
        // 此更新放在最前面 因为如果更新了投稿状态后，查询此作者是否已经参与此专题就会一直都是已经参与的状态
        if ($check_mode == 1) {
            // 更新作品作者加入的专题数（如果作者先前已加入过专题（其它作品），则不再更新）
            // 查询此作者是否已经参与了当前专题
            $result_sele = db_query("SELECT `works`.`Author` 
                                     FROM `topic_works`,`works`
                                     WHERE `topic_works`.`TopicId` = {$topic_id} AND 
                                           `works`.`Author` = {$user_id} AND
                                           `works`.`Id` = `topic_works`.`WorkId` AND 
                                           `topic_works`.`State` = 1 
                                     LIMIT 1");
            if ($result_sele !== FALSE) {
                if ($result_sele->num_rows == 0) { //作者未加入过此专题
                    // 更新作品作者加入的专题数
                    $result_update = db_query("UPDATE `users` 
                                               SET `TopicCount` = `TopicCount` + 1
                                               WHERE `users`.`Id` = {$user_id} ");
                }
            } else {
                return db_rollback();
            }
        }

        $date = new DateTime();
        $date_time = $date->format('Y-m-d H:i:s');
        //更新专题下作品的投稿状态
        $result1 = db_query("UPDATE `topic_works` 
                             SET `State` = {$check_mode},
                                 `CheckDt` ='{$date_time}',
                                 `CheckUser` = {$_SESSION['user_id']} 
                             WHERE `TopicId` = {$topic_id} AND 
                                   `WorkId` = {$work_id}");
        if ($result1 !== true) {
            return db_rollback();
        }
        if (db_affected_rows() <= 0) {
            db_rollback();
            return '错误:提交的作品信息或专题信息不正确';
        }

        //更新专题中的作品数量 更新作者提醒消息的数量
        if ($check_mode == 1) {
            //如果为审核通过 专题的作品数+1 待审数-1 并增加作者提醒消息的数量
            //20170121 添加 审批通过的话 更新专题的最新作品id为当前审批的作品
            $sql_str = "UPDATE `topic`,`message_count` 
	                    SET `topic`.`WaitCheckCount` = `topic`.`WaitCheckCount` - 1, 
	                        `topic`.`WorksCount` = `topic`.`WorksCount` + 1,
                            `topic`.`LastWorkId` = {$work_id}, 
	                        `message_count`.`Remind` = `message_count`.`Remind` + 1,
                            `message_count`.`AllRemind` = `message_count`.`AllRemind` + 1
	                    WHERE `topic`.`Id` = {$topic_id} AND 
	                          `message_count`.`UserId` = {$user_id}";
        } else {
            //如果为拒绝，待审数-1 并增加作者提醒消息的数量
            $sql_str = "UPDATE `topic`,`message_count` 
	                    SET `topic`.`WaitCheckCount` = `topic`.`WaitCheckCount` - 1,
	                        `message_count`.`Remind` = `message_count`.`Remind` + 1,
                            `message_count`.`AllRemind` = `message_count`.`AllRemind` + 1
	                    WHERE `topic`.`Id` = {$topic_id} AND 
	                          `message_count`.`UserId` = {$user_id}";
        }
        $result2 = db_query($sql_str);
        if ($result2 !== true) {
            return db_rollback();
        }
        // 给作者推送提醒消息
        $result3 = db_query("INSERT INTO `message_remind` 
                             SET `Type` = 1,
                                 `MsgIdFrom` = {$work_id},
                                 `MsgIdTo` = {$topic_id},
                                 `UserId` = {$user_id} 
                             ON DUPLICATE KEY UPDATE `MsgDt` = CURRENT_TIMESTAMP");
        if ($result3 === false) {
            return db_rollback();
        }

        $op = new user_operate();
        $result1 = $op->operate_save(user_operate::WorkForTopic, $user_id, $topic_id);
        if ($result1 !== TRUE) {
            db_rollback();
            return $result1;
        }
        db_commit();
        return $check_mode;
    }

    /**
     * 删除专题 成功返回'1' 失败返回错误信息
     * @param int $topic_id 专题Id
     * @param string $root 专题图片的路径最后含'/'
     */
    function topic_dele($topic_id, $root)
    {
        if (!is_numeric($topic_id)) {
            return '提交的专题信息错误';
        }
        //检查当前用户是否为管理员
        if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] < 90) {
            return '无权限删除专题';
        }
        db_begin();
        //获取本专题信息
        $result_sele = db_query("SELECT * FROM `topic` 
		                                   WHERE `Id` = {$topic_id} FOR UPDATE");
        if ($result_sele !== FALSE) {
            if ($result_sele->num_rows > 0 && $topicMsg = $result_sele->fetch_object()) {

            } else {
                return '未查询到要删除的专题';
            }
        } else {
            return db_rollback();
        }
        //删除掉专题
        $result_dele = db_query("DELETE FROM `topic` WHERE `Id` = {$topic_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        if (db_affected_rows() <= 0) {
            return '未找到要删除的专题';
        }
        //查询专题的作品的作者和审核状态
        $result_sele = db_query("SELECT `topic_works`.`State`,`works`.`Author` 
			                               FROM `topic_works`,`works` 
			                               WHERE `topic_works`.`TopicId` = {$topic_id} AND 
			                                     `works`.`Id` = `topic_works`.`WorkId` 
			                               FOR UPDATE");
        if ($result_sele !== FALSE) {
            $topicCountUpdate = array();
            $remindDele = array();
            $deleCount = 0;
            while ($row = $result_sele->fetch_object()) {
                //如果作品状态为已审核，且尚未更新作者加入的专题数 每个作者仅更新一次
                if ($row->State == 1 && !isset($topicCountUpdate[$row->Author])) {
                    $result_update = db_query("UPDATE `users` SET `TopicCount` = `TopicCount` - 1 
	                                                     WHERE `Id` = {$row->Author}");
                    if ($result_update === FALSE) {
                        return db_rollback();
                    }
                    $topicCountUpdate[$row->Author] = TRUE;
                }
                //删除相关作者的关于此专题的提醒消息  每个作者仅删除一次
                if (!isset($remindDele[$row->Author])) {
                    $result_dele = db_query("DELETE FROM `message_remind` 
                                             WHERE `MsgIdTo` = {$topic_id} AND 
                                                   `UserId` = {$row->Author}");
                    if ($result_dele === FALSE) {
                        return db_rollback();
                    }
                    // 更新相关作者的提醒消息总数量
                    $deleCount = db_affected_rows();
                    if ($deleCount > 0) {
                        $sql_str = "UPDATE `message_count` 
                                    SET `AllRemind` = `AllRemind` - {$deleCount}
                                    WHERE `UserId` = {$row->Author}";
                        $result_dele = db_query($sql_str);
                        if ($result_dele === false) return db_rollback();
                    }
                    $remindDele[$row->Author] = TRUE;
                }
            }
        } else {
            return db_rollback();
        }

        //删除专题的投稿、审核信息
        $result_dele = db_query("DELETE FROM `topic_works` 
		                                          WHERE `TopicId` = {$topic_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        //删除专题的关注
        $result_dele = db_query("DELETE FROM `topic_up` 
		                                          WHERE `TopicId` = {$topic_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        //删除专题的图片
        $topicImgs = explode(';', rtrim($topicMsg->Picture, ';'));
        foreach ($topicImgs as $topicImg) {
            //缩略图
            $fileName = $root . make_img_name::make_img_mini_name($topicImg);
            if (file_exists($fileName)) {
                unlink($fileName);
            }
            //原图
            $fileName = $root . $topicImg;
            if (file_exists($fileName)) {
                unlink($fileName);
            }
        }
        //以上操作全部正常
        db_commit();
        return '1';
    }

    /**
     * 保存专题 成功返回1 错误返回错误信息
     */
    function topic_save(&$data)
    {
        if (!$_SESSION["user_level"]) {
            return "错误:请登录";
        }
        if (!isset($data["topic_state"]) || ($data["topic_state"] != 1 && $data["topic_state"] != 0)) {
            return "错误:提交的专题状态不允许";
        } elseif (!isset($data['topic_name']) || !isset($data['introd'])) {
            return "错误:提交的专题信息不完全";
        }
        $data['topic_name'] = urldecode($data['topic_name']);
        $data['topic_name'] = db_escape($data['topic_name']);
        $data['introd'] = db_escape(urldecode($data['introd']));
        $name_len = mb_strlen($data['topic_name'], 'utf8');
        if ($name_len < 4) {
            return "错误:提交的专题名称少于4字符";
        } elseif ($name_len > 15) {
            return "错误:提交的专题名称超过15字符";
        }

        $introd_len = mb_strlen($data['introd'], 'utf8');
        if ($introd_len > 135) {
            return "错误:提交的专题简介超过135字符";
        } elseif ($introd_len < 4) {
            return "错误:提交的专题简介少于4字符";
        }
        //20170111 添加 获取专题名+简介的分词
        //获取的分词用空格分隔后 写入Keyword字段 用于搜索
        global $CfgPara;
        $keyWord = "{$data['topic_name']} {$data['introd']}";
        require_once("{$CfgPara->root}/class/keyword_zh.func.php");
        $keyWord = get_keywords($keyWord);
        //print($keyWord);
        if (isset($data["topic_id"]) && $data['topic_id'] > 0) //更新
        {
            return $this->topic_edit_update($data, $keyWord);
        } else //插入
        {
            return $this->topic_edit_insert($data, $keyWord);
        }
    }

    function topic_edit_update(&$data, &$keyWord)
    {
        if (!is_numeric($data["topic_id"])) {
            return "错误:提交的专题信息错误";
        }
        global $CfgPara;
        $imgs = do_edit_img(
            3, $data["topic_img_names"],
            "{$CfgPara->root}/topic_pic/", 'topic', 'Picture',
            $data['topic_id']);
        if ($imgs === false) return '处理上传文件时错误';
        $sql_str = "UPDATE `topic` SET 
                    `Name`='{$data['topic_name']}',
                    `Introd`='{$data['introd']}',
                    `State`={$data['topic_state']},
                    `Keyword` = '{$keyWord}',
                    `Picture`='{$imgs}' 
                    WHERE `Id` = '{$data['topic_id']}'";
        $result = db_query($sql_str);
        if ($result === true) {
            return 1;
        } else {
            return db_error();
        }
    }


    function topic_edit_insert(&$data, &$keyWord)
    {
        if (count($data["topic_img_names"]) <= 0) {
            return "错误:专题尚未提交图片";
        }
        global $CfgPara;
        $imgs = do_edit_img(
            3, $data["topic_img_names"],
            "{$CfgPara->root}/topic_pic/", 'topic', 'Picture');
        $sql_str = "INSERT INTO `topic` 
                    SET `Name`='{$data['topic_name']}',
                        `Introd`='{$data['introd']}',
                        `State`='{$data['topic_state']}',
                        `Keyword` = '{$keyWord}',
                        `Picture`='{$imgs}'";
        $result = db_query($sql_str);
        if ($result === true) {
            return 1;
        } else {
            return db_error();
        }
    }

    /**
     * 检测当前用户是否已参与专题的推荐 错误时提示错误信息
     * @param int $topic_id
     * @return bool|string
     */
    function topic_recommend_check($topic_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($topic_id)) {
            return "检查是否已推荐时:提交的信息错误";
        }
        $result = db_query("SELECT `TopicId` FROM `topic_up` WHERE `TopicId` = {$topic_id} AND `UserId` = {$_SESSION['user_id']} LIMIT 1");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }
}
